package mongo

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
	"xia/demo/model"
)

var mgoCli *mongo.Client

func initDb() {
	var err error
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
	//连接mongodb

	mgoCli, err = mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}
	//检查连接
	err = mgoCli.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
}
func MgoCli() *mongo.Client {
	if mgoCli == nil {
		initDb()
	}
	return mgoCli
}

func Get() {
}
func Set(stockName string, stockId string, nowPrice string, rate string) {
	var (
		client     = MgoCli()
		err        error
		collection *mongo.Collection
		iResult    *mongo.InsertOneResult
		id         primitive.ObjectID
	)
	collection = client.Database("xia_db").Collection("qi_collection")

	stock := model.Stock{
		StockName: stockName,
		StockId:   stockId,
		SD: model.StockDetails{
			NowPrice: nowPrice,
			Rate:     rate,
		},
	}
	if iResult, err = collection.InsertOne(context.TODO(), stock); err != nil {
		fmt.Print(err)
		return
	}
	id = iResult.InsertedID.(primitive.ObjectID)
	fmt.Println("自增ID", id.Hex())
}
